package com.zhongkai.web.control.config;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhongkai.model.config.Role;
import com.zhongkai.model.config.User;
import com.zhongkai.service.config.DepartmentService;
import com.zhongkai.service.config.RoleService;
import com.zhongkai.service.config.UserService;
import com.zhongkai.tools.CheckWord;
import com.zhongkai.tools.StringTool;

@Controller
public class UserController {
	private Logger log=Logger.getLogger(this.getClass());
	private UserService userService;
	private DepartmentService departmentService;
	private RoleService roleService;
	
	@Resource
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}
	
	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@Resource
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	
	/*保存*/
	@RequestMapping(value="/system/config/user_add.do")
	public String save(User user,Integer[] roleIds,HttpServletRequest request,HttpServletResponse response) throws IOException{
		try {
			PrintWriter out=response.getWriter();
			//编号校验
			if(user.getUserIdentifier()==null){
				out.write(CheckWord.showMsg("用户编号不能为空!","/system/config/user_add_form.jsp",request));
				return null;
			}
			Pattern pattern = Pattern.compile("^\\d{1,11}$");
			if(!pattern.matcher(user.getUserIdentifier()).matches()){
				out.write(CheckWord.showMsg("非法的编号格式!", "/system/config/user_add_form.jsp",request));
				return null;
			}
			List checkAccount=userService.findByHql("from User where userIdentifier=?", new Object[]{user.getUserIdentifier()});
			if(checkAccount!=null && checkAccount.size()>0){
				out.write(CheckWord.showMsg("该用户编号已被使用!", "/system/config/user_add_form.jsp",request));
				return null;
			}
			//角色校验
			if(roleIds==null||"".equals(user.getRoleId())){
				out.write(CheckWord.showMsg("角色不能为空!","/system/config/user_add_form.jsp",request));
				return null;
			}
			//部门校验
			if(user.getDepartmentId()==null||"".equals(user.getDepartmentId())){
				out.write(CheckWord.showMsg("部门不能为空!","/system/config/user_add_form.jsp",request));
				return null;
			}
			
			//角色id的链表
			List<Integer> roleIdList=Arrays.asList(roleIds);//数组转换成List
			String userAccount=user.getUserAccount();
			//用户名校验
			if(userAccount==null || "".equals(userAccount)){
				out.write(CheckWord.showMsg("用户名不能为空!", "/system/config/user_add_form.jsp",request));
				return null;
			}
			checkAccount=userService.findByHql("from User where userAccount=?", new Object[]{userAccount});
			if(checkAccount!=null && checkAccount.size()>0){
				out.write(CheckWord.showMsg("该用户名已被使用!", "/system/config/user_add_form.jsp",request));
				return null;
			}
			//密码校验
			String userPassword=user.getUserPassword();
			if(userPassword==null || "".equals(userPassword)){
				out.write(CheckWord.showMsg("密码不能为空!", "/system/config/user_add_form.jsp",request));
				return null;
			}
			else{
				//校验通过后准备保存
				User saveUser=new User();
				BeanUtils.copyProperties(user, saveUser);
				saveUser.setUserPassword(StringTool.encrypt(userPassword));
				saveUser.setDepartmentId(user.getDepartmentId());//设部门id，必设
				List roleList=roleService.findAll();
				String idStr="";//记录角色多个id
				if(roleList!=null&&roleList.size()>0){
					Iterator<Role> role_iter=roleList.iterator();
					//构造数据库出来的角色id链表
					List currentRoleIdList=new ArrayList<Integer>();
					while(role_iter.hasNext()){
						currentRoleIdList.add(role_iter.next().getRoleId());
					}
					if(currentRoleIdList.containsAll(roleIdList)){
						int i=0;
						while(i<roleIdList.size()){
							idStr+=roleIdList.get(i)+",";
							i++;
						}
						idStr=idStr.substring(0,idStr.length()-1);//形如：1,2,3,取其中的1,2,3
					}
				}
				
				saveUser.setRoleId(idStr);//设角色id，必设
				userService.save(saveUser);
				return "/system/config/user_manage_list.jsp";
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			PrintWriter out=response.getWriter();
			out.write(CheckWord.showMsg("注册时发生异常，请与管理员联系!", "/system/config/user_add_form.jsp",request));
			return null;
		}
	}
	
	/*删除*/
	@RequestMapping(value="/system/config/user_manage_delete.do")
	public String delete(HttpServletRequest request,HttpServletResponse response,int userId) throws IOException {
		try {
			User currentUser=userService.findById(userId);
			PrintWriter out=response.getWriter();
			if(currentUser==null){
				out.write(CheckWord.showMsg("该记录不存在!!", "/system/config/user_manage_list.jsp",request));
				return null;
			}
			else{
				userService.delete(currentUser);
				out.write(CheckWord.showMsg("删除成功!!", "/system/config/user_manage_list.jsp",request));
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			PrintWriter out=response.getWriter();
			out.write(CheckWord.showMsg("删除时出现异常，请与管理员联系!", "/system/config/user_manage_list.jsp",request));
			return null;
		}
	}
		
	/*更新*/
	@RequestMapping(value="/system/config/user_manage_modify.do")
	public String update(HttpServletResponse response,HttpServletRequest request,User user,Integer[]roleIds) throws Exception{
		try {
			PrintWriter out=response.getWriter();
			//编号校验
			if(user.getUserIdentifier()==null){
				out.write(CheckWord.showMsg("用户编号不能为空!","/system/config/user_manage_modify.jsp?userId="+user.getUserId(),request));
				return null;
			}
			Pattern pattern = Pattern.compile("^\\d{1,11}$");
			if(!pattern.matcher(user.getUserIdentifier()).matches()){
				out.write(CheckWord.showMsg("编号过长或非法!", "/system/config/user_manage_modify.jsp?userId="+user.getUserId(),request));
				return null;
			}
			List checkAccount=userService.findByHql("from User where userIdentifier=?", new Object[]{user.getUserIdentifier()});
			if(checkAccount!=null && checkAccount.size()>0){
				out.write(CheckWord.showMsg("该用户编号已被使用!","/system/config/user_manage_modify.jsp?userId="+user.getUserId(),request));
				return null;
			}
			/*角色校验*/
			if(roleIds==null){
				out.write(CheckWord.showMsg("角色不能为空!","/system/config/user_manage_modify.jsp?userId="+user.getUserId(),request));
				return null;
			}
			//角色id的链表
			List<Integer> roleIdList=Arrays.asList(roleIds);//数组转换成List
			/*密码校验*/
			if(user.getUserPassword()==null||"".equals(user.getUserPassword())){
				out.write(CheckWord.showMsg("密码不能为空!","/system/config/user_manage_modify.jsp?userId="+user.getUserId(),request));
				return null;
			}else{
				User currentUser=userService.findById(user.getUserId());//查出该id的当前用户
				currentUser.setUserEmail(user.getUserEmail());
				currentUser.setUserNickname(user.getUserNickname());
				currentUser.setUserSwitch(user.getUserSwitch());
				currentUser.setDepartmentId(user.getDepartmentId());
				List roleList=roleService.findAll();//搜出全部roleId
				String idStr="";//记录角色多个id
				if(roleList!=null&&roleList.size()>0){
					Iterator<Role> role_iter=roleList.iterator();
					//构造数据库出来的角色id链表
					List currentRoleIdList=new ArrayList<Integer>();
					while(role_iter.hasNext()){
						currentRoleIdList.add(role_iter.next().getRoleId());
					}
					if(currentRoleIdList.containsAll(roleIdList)){//如果role表里包含了传进来的roleId方为真，防止非法注入
						int i=0;
						while(i<roleIdList.size()){
							idStr+=roleIdList.get(i)+",";
							i++;
						}
						idStr=idStr.substring(0,idStr.length()-1);//形如：1,2,3,取其中的1,2,3
					}
				}
				
				currentUser.setRoleId(idStr);//设角色id，必设
				//currentAdmin.setAdminAccount(admin.getAdminAccount());
				//如果密码改了就加密
				if(user.getUserPassword()!=null&&!currentUser.getUserPassword().equals(user.getUserPassword())&&!"".equals(user.getUserPassword())){
					currentUser.setUserPassword(StringTool.encrypt(user.getUserPassword()));
					
				}
				userService.update(currentUser);
				out.write(CheckWord.showMsg("更新成功!", "/system/config/user_manage_list.jsp",request));
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			PrintWriter out=response.getWriter();
			out.write(CheckWord.showMsg("更新时出现异常，请与管理员联系!", "/system/config/user_manage_list.jsp",request));
			return null;
		}
	}
	
	
	
}
